package com.wh.service.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.wh.beans.ConstVar;
import com.wh.beans.LoginInfoCookie;
import com.legend.utils.CookieUtils;
import com.legend.utils.DESCoder;
import org.apache.tools.ant.taskdefs.condition.Http;

public class CommonBo {
	Logger log = Logger.getRootLogger();
	private static CommonBo instance = null;

	/*
	 * 单例
	 */
	public static CommonBo getInstance() {
		if (instance == null) {
			synchronized (CommonBo.class) {
				if (instance == null) {
					instance = new CommonBo();
				}
			}
		}
		return instance;
	}

	/**
	 * 检查系统用户是否登录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 * @throws java.security.NoSuchAlgorithmException
	 */
	public LoginInfoCookie checkLogin(HttpServletRequest request) {
		Cookie cookie = CookieUtils.getCookieByName(request, ConstVar.SYS_USER_LOGIN_INFO);
		if (cookie != null) {
			log.debug("cookie值：" + cookie.getValue());
			String userStr="";
			try {
				userStr = DESCoder.decrypt(cookie.getValue(), DESCoder.KEY_STR);
			} catch (Exception e) {
				log.debug(e.getMessage());
				return null;
			}
			LoginInfoCookie loginCookie=JSONObject.parseObject(userStr,LoginInfoCookie.class);
			return loginCookie;
		}
		return null;
	}

    /**
     *
     * @param request
     * @return
     */
    public LoginInfoCookie checkWorkLogin(HttpServletRequest request) {
        Cookie cookie = CookieUtils.getCookieByName(request, ConstVar.WORK_USER_LOGIN_INFO);
        if (cookie != null) {
            log.debug("cookie值：" + cookie.getValue());
            String userStr="";
            try {
                userStr = DESCoder.decrypt(cookie.getValue(), DESCoder.KEY_STR);
            } catch (Exception e) {
                log.debug(e.getMessage());
                return null;
            }
            LoginInfoCookie loginCookie=null;
            try{
                loginCookie=JSONObject.parseObject(userStr,LoginInfoCookie.class);
            }catch (Exception e)
            {            }
            return loginCookie;
        }
        return null;
    }

    public void logout(HttpServletRequest request,HttpServletResponse response) {
        Cookie cookie = CookieUtils.getCookieByName(request, ConstVar.SYS_USER_LOGIN_INFO);
        if (cookie != null) {
            log.debug("cookie值：" + cookie.getValue());
            String userStr="";
            try {
                 CookieUtils.removeCookieByName(request,response,ConstVar.SYS_USER_LOGIN_INFO);
            } catch (Exception e) {
                log.debug(e.getMessage());
            }
        }
    }
}
